package com.spoto.oa.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.spoto.oa.model.Employee;

public class LoginFilter implements Filter {

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest res = (HttpServletRequest) request;
		HttpServletResponse rsp = (HttpServletResponse) response;
		HttpSession session = res.getSession();
		Employee loginEmployee = (Employee) session.getAttribute("login_emp");

		String request_uri = res.getRequestURI().toUpperCase();// 得到用户请求的URI
		String ctxPath = res.getContextPath();// 得到web应用程序的上下文路径
		String uri = request_uri.substring(ctxPath.length()); // 去除上下文路径，得到剩余部分的路径
		if (uri.indexOf("LOGIN") == -1 && !uri.endsWith("CSS")
				&& !uri.endsWith("PNG") && !uri.endsWith("JS")
				&& !uri.endsWith("JPG") && uri.indexOf("DWR") == -1
				&& loginEmployee == null) {
			rsp.sendRedirect("login_failed.jsp");
			return;
		} else {
			chain.doFilter(res, rsp);
		}
	}

}
